# backend/dependencies.py
from fastapi import Depends, HTTPException, status
from sqlalchemy.orm import Session
from backend.database import SessionLocal
from backend.utils.security import get_current_user
from backend.crud.user_crud import get_user_by_username
from backend.models import User, LibraryMember


# 数据库会话依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 当前用户依赖
async def get_current_active_user(
        current_user: str = Depends(get_current_user),
        db: Session = Depends(get_db)
):
    user = get_user_by_username(db, username=current_user)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在或未激活",
        )
    return user


# 书阁管理员依赖
def get_library_admin(
        library_id: int,
        current_user: User = Depends(get_current_active_user),
        db: Session = Depends(get_db)
):
    # 检查用户是否为书阁管理员
    member = db.query(LibraryMember).filter(
        LibraryMember.library_id == library_id,
        LibraryMember.user_id == current_user.id,
        LibraryMember.is_owner == True
    ).first()

    if not member:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权执行此操作",
        )
    return current_user
